package com.zdkj.subway.rca.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.rca.entity.SwCkStatementConfirmDailyticketCatConsume;
import com.zdkj.subway.rca.entity.SwCkStatementConfirmDailyticketCatConsumeTmp;
import com.zdkj.subway.rca.mapper.SwCkStatementConfirmDailyticketCatConsumeTmpMapper;
import com.zdkj.subway.rca.service.SwCkStatementConfirmDailyticketCatConsumeService;
import com.zdkj.subway.rca.service.SwCkStatementConfirmDailyticketCatConsumeTmpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.ZoneId;
import java.util.*;

/**
 * 长安通日票代售确认表临时表
 */
@Service
public class SwCkStatementConfirmDailyticketCatConsumeTmpServiceImpl extends ServiceImpl<SwCkStatementConfirmDailyticketCatConsumeTmpMapper,SwCkStatementConfirmDailyticketCatConsumeTmp> implements SwCkStatementConfirmDailyticketCatConsumeTmpService{
    private static final Logger LOGGER = LoggerFactory.getLogger(SwCkStatementConfirmDailyticketCatConsumeTmpServiceImpl.class);
    private String parsePattern = "yyyy-MM-dd";
    @Autowired
    private SwCkStatementConfirmDailyticketCatConsumeService swCkStatementConfirmDailyticketCatConsumeService;

    @Override
    public Boolean saveBatchWithExcel(final File excelFile) throws Exception {
        List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet().headRowNumber(8).doReadSync();
        if (CollectionUtil.isNotEmpty(listMap)) {
            List<SwCkStatementConfirmDailyticketCatConsumeTmp> listDb = new ArrayList<>();
            MultipartFileToFile.delteTempFile(excelFile);
            for (int m = 0; m < listMap.size(); m++) {
                Map<Integer, String> data = listMap.get(m);
                // 返回每条数据的键值对 表示所在的列 和所在列的值
                LOGGER.info("读取到数据:{}", JSON.toJSONString(data));

                SwCkStatementConfirmDailyticketCatConsumeTmp tmpObj = new SwCkStatementConfirmDailyticketCatConsumeTmp();
                tmpObj.setTradeDateTmp(data.get(0));//交易日期

                tmpObj.setOneticketCountTmp(Optional.ofNullable(data.get(1)).orElse("0"));
                tmpObj.setOneticketMoneyTmp(Optional.ofNullable(data.get(2)).orElse("0"));
                tmpObj.setOneticketStockCountTmp(Optional.ofNullable(data.get(3)).orElse("0"));
                tmpObj.setThirdticketCountTmp(Optional.ofNullable(data.get(4)).orElse("0"));

                tmpObj.setThirdticketMoneyTmp(Optional.ofNullable(data.get(5)).orElse("0"));
                tmpObj.setThirdticketStockCountTmp(Optional.ofNullable(data.get(6)).orElse("0"));
                tmpObj.setTotalCountTmp(Optional.ofNullable(data.get(7)).orElse("0"));
                tmpObj.setTotalMoneyTmp(Optional.ofNullable(data.get(8)).orElse("0"));

                tmpObj.setTotalStockCountTmp(Optional.ofNullable(data.get(9)).orElse("0"));

                if (StringUtils.isEmpty(tmpObj.getTradeDateTmp())
                        || StringUtils.isEmpty(tmpObj.getTotalCountTmp())
                        || StringUtils.isEmpty(tmpObj.getTotalMoneyTmp())
                        || StringUtils.isEmpty(tmpObj.getTotalStockCountTmp())
                ) {
                    continue;
                }
                if (!parseDate(tmpObj.getTradeDateTmp())) {
                    continue;
                }

                final SwCkStatementConfirmDailyticketCatConsumeTmp obj = ObjectUtils.getDefaultObj(SwCkStatementConfirmDailyticketCatConsumeTmp.class);
                BeanUtils.copyProperties(tmpObj, obj, "deptId", "creatorId", "creatorName");
                checkErr(obj);
                listDb.add(obj);

            }
            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("CREATOR_ID", listDb.get(0).getCreatorId());
            this.baseMapper.deleteByMap(columnMap);
            return this.saveBatch(listDb);

        }

        return false;
    }

    private void checkErr(SwCkStatementConfirmDailyticketCatConsumeTmp obj) {
        //更新字段
        String tradeDateTmp = obj.getTradeDateTmp();
        try {
            Date tradeDate = DateUtils.parseDate(tradeDateTmp, parsePattern);
            obj.setTradeDate(tradeDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
        } catch (Exception e) {
            obj.setErrMsg("交易日期 为空或格式错误");
        }

        try {
            String oneticketCountTmp = obj.getOneticketCountTmp();
            Long oneticketCount = Long.valueOf(oneticketCountTmp);
            obj.setOneticketCount(oneticketCount);

            String oneticketStockCountTmp = obj.getOneticketStockCountTmp();
            Long oneticketStockCount = Long.valueOf(oneticketStockCountTmp);
            obj.setOneticketStockCount(oneticketStockCount);

            String thirdticketCountTmp = obj.getThirdticketCountTmp();
            Long thirdticketCount = Long.valueOf(thirdticketCountTmp);
            obj.setThirdticketCount(thirdticketCount);

            String thirdticketStockCountTmp = obj.getThirdticketStockCountTmp();
            Long thirdticketStockCount = Long.valueOf(thirdticketStockCountTmp);
            obj.setThirdticketStockCount(thirdticketStockCount);

            String totalCountTmp = obj.getTotalCountTmp();
            Long totalCount = Long.valueOf(totalCountTmp);
            obj.setTotalCount(totalCount);

            String totalStockCountTmp = obj.getTotalStockCountTmp();
            Long totalStockCount = Long.valueOf(totalStockCountTmp);
            obj.setTotalStockCount(totalStockCount);

        } catch (Exception e) {
            obj.setErrMsg("数量 为空或格式错误");
        }

        try {
            BigDecimal num = new BigDecimal("100");

            String oneticketMoneyTmp = obj.getOneticketMoneyTmp();
            BigDecimal oneticketMoney = new BigDecimal(oneticketMoneyTmp);
            oneticketMoney = oneticketMoney.multiply(num);
            obj.setOneticketMoney(oneticketMoney.longValue());

            String thirdticketMoneyTmp = obj.getThirdticketMoneyTmp();
            BigDecimal thirdticketMoney = new BigDecimal(thirdticketMoneyTmp);
            thirdticketMoney = thirdticketMoney.multiply(num);
            obj.setThirdticketMoney(thirdticketMoney.longValue());

            String totalMoneyTmp = obj.getTotalMoneyTmp();
            BigDecimal totalMoney = new BigDecimal(totalMoneyTmp);
            totalMoney = totalMoney.multiply(num);
            obj.setTotalMoney(totalMoney.longValue());

        } catch (Exception e) {
            obj.setErrMsg("金额 为空或格式错误");
        }


        //判断数据是否存在
        SwCkStatementConfirmDailyticketCatConsume swCkStatementConfirmDailyticketCatConsume = new SwCkStatementConfirmDailyticketCatConsume();
        BeanUtils.copyProperties(obj, swCkStatementConfirmDailyticketCatConsume, "deptId","creatorId","creatorName","createTime");
        List<SwCkStatementConfirmDailyticketCatConsume> list = swCkStatementConfirmDailyticketCatConsumeService.list(Wrappers.query(swCkStatementConfirmDailyticketCatConsume));
        if (list != null && !list.isEmpty()) {
            obj.setErrMsg("数据已存在");
        }
    }

    private boolean parseDate(String string) {
        boolean convertSuccess = true;
        if (string == null) {
            return false;
        }

        try {
            String substring = string.substring(0, 10);
            DateUtils.parseDate(substring, parsePattern);
        } catch (ParseException e) {
            convertSuccess = false;
        }
        return convertSuccess;
    }

    @Override
    public void saveBatchWithExcelOk(Integer creatorId) {
        //导入先删除
        this.baseMapper.deleteBatchWithExcelOk(creatorId);
        //导入先删除再添加包括重复的
        this.baseMapper.saveBatchWithExcelOkRepeat(creatorId);
        //this.baseMapper.saveBatchWithExcelOk(creatorId);
        saveBatchWithExcelCancel(creatorId);
    }

    @Override
    public void saveBatchWithExcelCancel(Integer creatorId) {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("CREATOR_ID", creatorId);
        this.baseMapper.deleteByMap(columnMap);
    }
}
